package com.ocean.courtyard.listener;

import com.ocean.courtyard.CourtyardApplication;
import com.ocean.courtyard.constants.ConstantsAttribute;
import com.ocean.courtyard.entity.CourtyardHome;
import com.ocean.courtyard.util.FileUtils;
import net.william278.huskhomes.event.ReplyTeleportRequestEvent;
import net.william278.huskhomes.libraries.minedown.adventure.MineDown;
import net.william278.huskhomes.teleport.TeleportRequest;
import net.william278.huskhomes.user.OnlineUser;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;

public class WorldLimitListener implements Listener {

    private final CourtyardApplication plugin;

    public WorldLimitListener() {
        plugin = CourtyardApplication.getInstance();
    }

    /**
     * 接受传送方的监听事件
     *
     * @param event event
     */
    @EventHandler(priority = EventPriority.HIGHEST)
    public void onPlayerTeleport(ReplyTeleportRequestEvent event) {
        TeleportRequest request = event.getRequest();
        String requesterPlayerName = request.getRequesterName();

        if (request.getStatus() == TeleportRequest.Status.ACCEPTED) {
            OnlineUser recipient = event.getRecipient();
            String toWorldName = recipient.getPosition().getWorld().getName();
            FileConfiguration config = plugin.getConfig();

            // 如果世界在worldFolder配置的文件夹下，代表是一个私人世界
            if (toWorldName.startsWith(FileUtils.getWorldContainer(config))) {
                int maxHomePlayers = config.getInt(ConstantsAttribute.MAX_HOMES_LIMIT);
                CourtyardHome home = plugin.getSqlSession().getHome(requesterPlayerName);
                //不是自己的世界
                if (!toWorldName.equals(home.getWorldName())) {
                    CourtyardHome toWorldHome = plugin.getSqlSession().getHomeByWorldName(toWorldName);
                    Integer playerExists = plugin.getSqlSession().checkPlayerExists(toWorldHome.getHomeId(), requesterPlayerName);
                    if (playerExists == 0) {
//                        plugin.getMessage().sendNoPermission(player);
                        recipient.sendTitle(new MineDown("该玩家没有权限到这个世界，请先添加玩家许可！使用cy add [用户名]"), false);
                        //TODO 发送消息给发送者，需要跨服发送消息，因为有可能不在目标玩家的服务器
                        event.setCancelled(true);
                    }
                }
            }
        }
    }
}
